/*
 * Copyright (c) 2009 Piotr Piastucki
 * 
 * This file is part of Patchca CAPTCHA library.
 * 
 *  Patchca is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  Patchca is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Patchca. If not, see <http://www.gnu.org/licenses/>.
 */
package com.chenfei.captcha.utils.text;


import com.chenfei.captcha.utils.color.RandomColorFactory;

import java.awt.*;
import java.awt.image.BufferedImage;

public class TextRenderer {

	protected int leftMargin;
	protected int rightMargin;
	protected int topMargin;
	protected int bottomMargin;

	protected void arrangeCharacters(int width, int height, TextString ts) {
		double widthRemaining = (width - leftMargin - rightMargin) / ts.getCharacters().size();
		double x = leftMargin;
		height -= topMargin + bottomMargin;
		for (TextCharacter tc : ts.getCharacters()) {
			tc.setX(x);
			tc.setY(height);
			x += tc.getWidth() + widthRemaining;
		}
	}

	public TextRenderer() {
		leftMargin = rightMargin = 24;
		topMargin = bottomMargin = 8;
	}


	public void draw(String text, BufferedImage canvas, RandomColorFactory colorFactory) {
		Graphics2D g = (Graphics2D) canvas.getGraphics();
		TextString ts = convertToCharacters(text, colorFactory);
		arrangeCharacters(canvas.getWidth(), canvas.getHeight(), ts);
		for (TextCharacter tc : ts.getCharacters()) {
			g.setColor(tc.getColor());
			g.drawString(tc.iterator(), (float) tc.getX(), (float) tc.getY());
		}
	}

	protected TextString convertToCharacters(String text, RandomColorFactory colorFactory) {
		TextString characters = new TextString();
		for (int i = 0; i < text.length(); i++) {
			Font font = new Font(null, Font.PLAIN, 45);
			char c = text.charAt(i);
			TextCharacter tc = new TextCharacter();
			tc.setCharacter(c);
			tc.setFont(font);
			tc.setColor(colorFactory.getColor(i));
			characters.addCharacter(tc);
		}
		return characters;
	}

}
